package com.xunyin.modules.couponnew.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xunyin.api.XunyinException;
import com.xunyin.common.service.impl.BaseServiceImpl;
import com.xunyin.common.utils.QueryHelpPlus;
import com.xunyin.enums.StatusEnum;
import com.xunyin.modules.couponnew.domain.MtCoupon;
import com.xunyin.modules.couponnew.domain.MtCouponGroup;
import com.xunyin.modules.couponnew.service.CouponGroupService;
import com.xunyin.modules.couponnew.service.dto.GroupDataDto;
import com.xunyin.modules.couponnew.service.dto.ReqCouponGroupDto;
import com.xunyin.modules.couponnew.service.dto.MtCouponGroupQueryCriteria;
import com.xunyin.modules.couponnew.service.mapper.MtCouponGroupMapper;
import com.xunyin.modules.couponnew.service.mapper.MtCouponMapper;
import com.xunyin.pagination.PaginationRequest;
import com.xunyin.pagination.PaginationResponse;
import com.xunyin.utils.CommonUtilV;
import com.xunyin.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 卡券业务实现类
 * <p>
 * Created by xunyinyunshang <3594419785@qq.com>
 * CopyRight 讯音云商 https://www.tonetn.com
 */
@Service
@RequiredArgsConstructor
@Slf4j
//@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class CouponGroupServiceImpl extends BaseServiceImpl<MtCouponGroupMapper, MtCouponGroup> implements CouponGroupService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MtCouponGroupMapper mtCouponGroupMapper;

    @Autowired
    private MtCouponMapper mtCouponMapper;

    /**
     * 分页查询卡券分组列表
     *
     * @param paginationRequest
     * @return
     */
    @Override
    public PaginationResponse<MtCouponGroup> queryCouponGroupListByPagination(PaginationRequest paginationRequest) {
        Page<MtCouponGroup> pageHelper = PageHelper.startPage(paginationRequest.getCurrentPage(), paginationRequest.getPageSize());
        LambdaQueryWrapper<MtCouponGroup> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.ne(MtCouponGroup::getStatus, StatusEnum.DISABLE.getKey());

        String name = paginationRequest.getSearchParams().get("name") == null ? "" : paginationRequest.getSearchParams().get("name").toString();
        if (StringUtils.isNotBlank(name)) {
            lambdaQueryWrapper.like(MtCouponGroup::getName, name);
        }
        String status = paginationRequest.getSearchParams().get("status") == null ? "" : paginationRequest.getSearchParams().get("status").toString();
        if (StringUtils.isNotBlank(status)) {
            lambdaQueryWrapper.eq(MtCouponGroup::getStatus, status);
        }
        String id = paginationRequest.getSearchParams().get("id") == null ? "" : paginationRequest.getSearchParams().get("id").toString();
        if (StringUtils.isNotBlank(id)) {
            lambdaQueryWrapper.eq(MtCouponGroup::getId, id);
        }

        lambdaQueryWrapper.orderByDesc(MtCouponGroup::getId);
        List<MtCouponGroup> dataList = mtCouponGroupMapper.selectList(lambdaQueryWrapper);

        PageRequest pageRequest = PageRequest.of(paginationRequest.getCurrentPage(), paginationRequest.getPageSize());
        PageImpl pageImpl = new PageImpl(dataList, pageRequest, pageHelper.getTotal());
        PaginationResponse<MtCouponGroup> paginationResponse = new PaginationResponse(pageImpl, MtCouponGroup.class);
        paginationResponse.setTotalPages(pageHelper.getPages());
        paginationResponse.setTotalElements(pageHelper.getTotal());
        paginationResponse.setContent(dataList);

        return paginationResponse;
    }

    @Override
    public Map<String, Object> queryAll(MtCouponGroupQueryCriteria criteria, Pageable pageable) {
        getPage(pageable);
        PageInfo<MtCouponGroup> page = new PageInfo<>(queryAll(criteria));
        Map<String, Object> map = new LinkedHashMap<>(2);
        map.put("content", page.getList());
        map.put("totalElements", page.getTotal());
        return map;
    }

    @Override
    public List<MtCouponGroup> queryAll(MtCouponGroupQueryCriteria criteria) {
        return baseMapper.selectList(QueryHelpPlus.getPredicate(MtCouponGroup.class, criteria));
    }

    /**
     * 添加卡券分组
     *
     * @param reqCouponGroupDto
     */
    @Override
    //@OperationServiceLog(description = "新增卡券分组")
    public MtCouponGroup addCouponGroup(ReqCouponGroupDto reqCouponGroupDto) {
        MtCouponGroup couponGroup = new MtCouponGroup();

        couponGroup.setName(CommonUtilV.replaceXSS(reqCouponGroupDto.getName()));
        couponGroup.setMoney(new BigDecimal("0"));
        couponGroup.setTotal(0);
        couponGroup.setDescription(CommonUtilV.replaceXSS(reqCouponGroupDto.getDescription()));
        couponGroup.setStatus(StatusEnum.ENABLED.getKey());
        couponGroup.setCreateTime(new Date());
        couponGroup.setUpdateTime(new Date());
        couponGroup.setNum(0);
        couponGroup.setOperator(reqCouponGroupDto.getOperator());

        this.save(couponGroup);
        return couponGroup;
    }

    /**
     * 根据分组ID获取卡券分组信息
     *
     * @param id 卡券分组ID
     */
    @Override
    public MtCouponGroup queryCouponGroupById(Integer id) {
        return mtCouponGroupMapper.selectById(id);
    }


    /**
     * 修改卡券分组
     *
     * @param reqcouponGroupDto
     */
    @Override
    @Transactional
    //@OperationServiceLog(description = "更新卡券分组")
    public MtCouponGroup updateCouponGroup(ReqCouponGroupDto reqcouponGroupDto) {
        MtCouponGroup couponGroup = this.queryCouponGroupById(reqcouponGroupDto.getId());
        if (null == couponGroup || StatusEnum.DISABLE.getKey().equalsIgnoreCase(couponGroup.getStatus())) {
            log.error("该分组不存在或已被删除");
            //throw new BusinessCheckException("该分组不存在或已被删除");
            throw new XunyinException("该分组不存在或已被删除");
        }
        if (reqcouponGroupDto.getName() != null) {
            couponGroup.setName(CommonUtilV.replaceXSS(reqcouponGroupDto.getName()));
        }
        if (reqcouponGroupDto.getDescription() != null) {
            couponGroup.setDescription(CommonUtilV.replaceXSS(reqcouponGroupDto.getDescription()));
        }
        if (couponGroup.getTotal() == null) {
            couponGroup.setTotal(0);
        }
        if (reqcouponGroupDto.getStatus() != null) {
            couponGroup.setStatus(reqcouponGroupDto.getStatus());
        }

        couponGroup.setUpdateTime(new Date());
        couponGroup.setOperator(reqcouponGroupDto.getOperator());

        this.updateById(couponGroup);

        return couponGroup;
    }

    /**
     * 根据ID删除卡券分组
     *
     * @param id       分组ID
     * @param operator 操作人
     */
    @Override
    //@OperationServiceLog(description = "删除卡券分组")
    public void deleteCouponGroup(Integer id, String operator) {
        MtCouponGroup couponGroup = this.queryCouponGroupById(id);
        if (null == couponGroup) {
            return;
        }

        couponGroup.setStatus(StatusEnum.DISABLE.getKey());
        couponGroup.setUpdateTime(new Date());
        couponGroup.setOperator(operator);

        this.updateById(couponGroup);
    }

    /**
     * 获取卡券种类数量
     *
     * @param id
     */
    @Override
    @Transactional
    public Integer getCouponNum(Integer id) {
        Long num = mtCouponMapper.queryNumByGroupId(id);
        return num.intValue();
    }

    /**
     * 获取卡券总价值
     *
     * @param groupId
     */
    @Override
    @Transactional
    public BigDecimal getCouponMoney(Integer groupId) {
        List<MtCoupon> couponList = mtCouponMapper.queryByGroupId(groupId.intValue());
        MtCouponGroup groupInfo = this.queryCouponGroupById(groupId);
        BigDecimal money = BigDecimal.valueOf(0);
        if (couponList.size() > 0) {
            for (int i = 0; i < couponList.size(); i++) {
                BigDecimal number = couponList.get(i).getAmount().multiply(BigDecimal.valueOf(couponList.get(i).getSendNum()));
                number = number.multiply(BigDecimal.valueOf(groupInfo.getTotal()));
                money = money.add(number);
            }
        }
        return money;
    }

    /**
     * 获取已发放套数
     *
     * @param couponId 卡券ID
     */
    @Override
    public Integer getSendNum(Integer couponId) {
        //Long num = mtUserCouponMapper.getSendNum(couponId);
        //return num.intValue();
        return null;
    }

    @Override
    public String importSendCoupon(MultipartFile file, String operator, String filePath) {
        return null;
    }

    @Override
    public String saveExcelFile(MultipartFile file, HttpServletRequest request) throws Exception {
        return null;
    }

    @Override
    public GroupDataDto getGroupData(Integer groupId, HttpServletRequest request, Model model) {
        return null;
    }
}
